package com.oa.hyperion.api.v1;

import com.auth0.jwt.interfaces.Claim;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.oa.hyperion.entity.User;
import com.oa.hyperion.entity.UserFrom;
import com.oa.hyperion.exception.http.ForbiddenException;

import com.oa.hyperion.service.UserService;
import com.oa.hyperion.utils.IpAdrressUtil;
import com.oa.hyperion.utils.JwtUtils;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.models.auth.In;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;


import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Api(value = "用户基本功能",tags = "用户基本功能")
@RestController
@RequestMapping("/v1/user")
public class UserController {
     @Resource
    private UserService userService;
     @ApiOperation("增加用户")
     @PostMapping("add")
    public User addUser(@RequestBody @Valid @ApiParam(name = "user",value = "新增的用户") User user){
            // 查询用户是否存在
        if(user==null||user.getAccount()==null){
            // 抛出传参不正确异常
            throw new ForbiddenException(50001);
        }
        //用户存在进一步判读用户名是否存在
        String account = user.getAccount();
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("account",account);
        User userFind = userService.getOne(wrapper);
        //用户存在抛出异常
        if(userFind!=null){
            //抛出用户存在异常
            throw  new ForbiddenException(50004);
        }
        //用户不存在添加用户
        //设置加密密码
        SimpleHash simpleHash = new SimpleHash("md5",user.getPassword(),user.getAccount(),1024);
        String s = simpleHash.toHex();
        user.setPassword(s);
        //将用户添加到数据库中
        user.setCreateTime(new Date());
        user.setStatus("y");
        userService.saveOrUpdate(user);
        return user;
    }

    @ApiOperation("用户登录")
    @PostMapping("login")
    public String loginUser(@RequestBody @Valid @ApiParam(name = "user",value = "页面登录用户") User user, HttpServletRequest request){
        //判断数据库中的用户状态是否为“y”,为"y"继续验证
        String password = user.getPassword();//传入的密码
        UsernamePasswordToken sysUserPasswordToken =  new UsernamePasswordToken(user.getAccount(),password.toCharArray());
        Subject subject = SecurityUtils.getSubject();
            try {
                subject.login(sysUserPasswordToken);
                //更新用户最后一次登录时间以及登录的ip地址
                User user1 = (User) subject.getPrincipal();
                Date date  = new Date();
                String ip = IpAdrressUtil.getIpAdrress(request);
                user1.setLastLoginIp(ip);
                user1.setLastLoginTime(date);
                userService.saveOrUpdate(user1);
                //登录成功之后
                String jwt = JwtUtils.createJwt(user1.getId());
                return jwt;
            }catch (AuthenticationException e){
                e.printStackTrace();
                throw new ForbiddenException(50002);
            }

    }
    @ApiOperation("改变用户状态")
    @PostMapping ("modifyStatus")
    public void deleteUser(@RequestBody @ApiParam(name = "ids",value = "改变用户状态的id数组") UserFrom from){
//        System.out.println(ids);
//        List<Integer> iDs = Arrays.asList(ids);
        List<User> users = userService.listByIds(Arrays.asList(from.getIds()));
        for(User user:users){
            user.setStatus("n");
            userService.saveOrUpdate(user);
        }
    }

    /**
     * 查询所有用户
     * @return
     */
    @ApiOperation("查询所有可用用户")
    @GetMapping("findAllEnable/{pageNum}")
    public PageInfo<User> findAllUsers(@PathVariable int pageNum){
        if(pageNum==0){
            pageNum=1;
        }
        PageHelper.startPage(pageNum,3);
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("status","y");
         List<User> users = userService.list(wrapper);
         return  new PageInfo<>(users);
    }
    @ApiOperation("查询所有用户")
    @GetMapping("findAll/{pageNum}")
    public PageInfo<User> findAll(@PathVariable int pageNum){
        if(pageNum==0){
            pageNum=1;
        }
        PageHelper.startPage(pageNum,2);
        List<User> users = userService.list(null);
        return  new PageInfo<>(users);
    }

    /**
     * 更新用户信息
     * @param user
     * @return
     */
    @ApiOperation("更新指定用户")
    @PutMapping("update")
    public void updateUser(@RequestBody @Valid @ApiParam(name = "user",value = "需要更新的用户") User user, HttpServletRequest request, HttpServletResponse response){
        String account = user.getAccount();
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("account",account);
        User one = userService.getOne(wrapper);
        if(one != null){
            throw  new ForbiddenException(50004);
        }
        SimpleHash simpleHash = new SimpleHash("md5",user.getPassword(),user.getAccount(),1024);
        String s = simpleHash.toHex();
        user.setPassword(s);
        userService.saveOrUpdate(user);
//        return "redirect:/v1/user/findAllEnable";
    }

    /**
     * 根据用户名模糊查询用户
     * @param account
     * @return
     */
    @ApiOperation("模糊查询用户")
    @GetMapping("findByCondition/{pageNum}")
    public PageInfo<User> findUserByCondition(@PathVariable int pageNum,@ApiParam(name = "account",value = "模糊查询用户") String account){
        if(pageNum==0){
            pageNum=1;
        }
        PageHelper.startPage(pageNum,2);
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("status","y");
        wrapper.like("account",account);
        List<User> users = userService.list(wrapper);
        return new PageInfo<>(users);
    }
    @ApiOperation("根据jwt查询用户")
    @GetMapping("findByJwt")
    public User findUserByJwt(@ApiParam(name = "jwt",value = "传入的jwt")@RequestHeader("Authorization")String  jwt){
        String result = jwt.split(" ")[1];
        Map<String, Claim> claim = JwtUtils.getClaim(result);
        if(claim==null){
            throw new ForbiddenException(50003);
        }
        Claim claims = claim.get("id");
        int id = claims.asInt();
       return userService.getById(id);
    }
}
